import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex) //vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
  state: {
    // 购物车数组
    cartList: uni.getStorageSync('cartList') || [],
  },
  mutations: {
    setCartList(state, cartList) {
      state.cartList = cartList
      uni.setStorageSync('cartList', cartList)
    },
  },
  getters: {
    // 总价格
    totalPrice(state) {
      let price = 0
      state.cartList.forEach(goods => {
        if (goods.checked) {
          price += goods.nums * goods.goods_price
        }
      })
      return price
    },
    // 总数量
    totalNum(state) {
      let num = 0
      state.cartList.forEach(goods => {
        if (goods.checked) {
          num += goods.nums
        }
      })
      return num
    },
    // 用户待结算的商品数组 - 勾选了的商品
    checkedCartList(state) {
      return state.cartList.filter(goods => goods.checked)
    },
  },
  // vuex 中的计算属性
})
export default store
